package com.youlai.boot.system.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.system.converter.DailySalesReportConverter;
import com.youlai.boot.system.mapper.DailySalesReportMapper;
import com.youlai.boot.system.model.entity.DailySalesReport;
import com.youlai.boot.system.model.form.DailySalesReportForm;
import com.youlai.boot.system.model.query.DailySalesReportQuery;
import com.youlai.boot.system.model.vo.DailySalesReportVO;
import com.youlai.boot.system.service.DailySalesReportService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * TP运营日报服务实现类
 *
 * @author xiheforever
 * @since 2025-05-13 10:02
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class DailySalesReportServiceImpl extends ServiceImpl<DailySalesReportMapper, DailySalesReport> implements DailySalesReportService {

    private final DailySalesReportConverter dailySalesReportConverter;

    /**
    * 获取TP运营日报分页列表
    *
    * @param queryParams 查询参数
    * @return {@link IPage<DailySalesReportVO>} TP运营日报分页列表
    */
    @Override
    public IPage<DailySalesReportVO> getDailySalesReportPage(DailySalesReportQuery queryParams) {
        Page<DailySalesReportVO> pageVO = this.baseMapper.getDailySalesReportPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }

    /**
     * 获取TP运营日报表单数据
     *
     * @param id TP运营日报ID
     * @return TP运营日报表单数据
     */
    @Override
    public DailySalesReportForm getDailySalesReportFormData(Long id) {
        DailySalesReport entity = this.getById(id);
        return dailySalesReportConverter.toForm(entity);
    }

    /**
     * 新增TP运营日报
     *
     * @param formData TP运营日报表单对象
     * @return 是否新增成功
     */
    @Override
    public boolean saveDailySalesReport(DailySalesReportForm formData) {
        DailySalesReport entity = dailySalesReportConverter.toEntity(formData);
        return this.save(entity);
    }

    /**
     * 更新TP运营日报
     *
     * @param id   TP运营日报ID
     * @param formData TP运营日报表单对象
     * @return 是否修改成功
     */
    @Override
    public boolean updateDailySalesReport(Long id,DailySalesReportForm formData) {
        DailySalesReport entity = dailySalesReportConverter.toEntity(formData);
        return this.updateById(entity);
    }

    /**
     * 删除TP运营日报
     *
     * @param ids TP运营日报ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    public boolean deleteDailySalesReports(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的TP运营日报数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

    /**
     * 获取可用的报告日期列表
     *
     * @return 可用日期列表，按降序排列
     */
    @Override
    public List<String> getAvailableDates() {
        try {
            LambdaQueryWrapper<DailySalesReport> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(DailySalesReport::getReportDate)
                    .orderByDesc(DailySalesReport::getReportDate);
            
            List<DailySalesReport> reports = this.list(queryWrapper);
            
            if (reports == null || reports.isEmpty()) {
                return new ArrayList<>(); // 返回空列表而非null
            }
            
            return reports.stream()
                    .map(report -> report.getReportDate() != null ? 
                         report.getReportDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) : null)
                    .filter(Objects::nonNull)  // 过滤掉null值
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取可用日期列表失败", e);
            return new ArrayList<>(); // 异常情况下返回空列表
        }
    }

    /**
     * 根据日期获取日报详情
     *
     * @param date 报告日期，格式：YYYY-MM-DD
     * @return 日报详情数据
     */
    @Override
    public DailySalesReportVO getDailySalesReportByDate(String date) {
        try {
            Assert.isTrue(StrUtil.isNotBlank(date), "查询日期不能为空");
            
            LocalDate reportDate = LocalDate.parse(date);
            LambdaQueryWrapper<DailySalesReport> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DailySalesReport::getReportDate, reportDate);
            
            DailySalesReport entity = this.getOne(queryWrapper);
            if (entity == null) {
                return null; // 返回null而非抛出异常
            }
            
            DailySalesReportVO vo = dailySalesReportConverter.toVO(entity);
            // 确保更新时间不为空，即使原始数据没有
            if (vo.getUpdateTime() == null) {
                vo.setUpdateTime(LocalDateTime.now());
            }
            
            return vo;
        } catch (Exception e) {
            log.error("根据日期获取日报详情失败，日期: {}", date, e);
            return null; // 异常情况下返回null
        }
    }

}
